var $permissionPanel=$("#userPermission");
var $department=$("#department");
var $roleName=$("#roleName");
var $permission="";
//创建部门和职务联动的下拉列表
common.buildInitSelect($roleName);
buildSelect.buildRoleListByDepartment({
    departmentSelector:$department,
    roleSelector:$roleName,
    fatherSelectorChange:function (fatherSelector,sonSelector) {
        var RoleId=sonSelector.val();
        var permissionIdArr=[];
        handler({
            roleId:RoleId,
            PermissionList:permissionIdArr,
            permissionSelector:$permission
        });
    }
});

//根据接权限菜单接口获取权限菜单列表，初始化所有的权限菜单为灰色未选择状态
$.post(window.globalHost + '/agent-sys/admin/menu/index.do',{status:"AVAILABLE"}).success(function(data) {
    //将返回数据进行提取，获取权限列表数据源
    var record=common.transformData(data);
    var permissionList=[];
    $.each(record,function (i, ele) {
        //获取子级权限名称列表
        var sonList=ele['subMenu'];
        var domStr="";
        //如果当前子级权限名称列表是有值的，那么就遍历该子级列表，组装DOM结构，为标签挂载相关属性
        //data-selfId:权限id,data-upId:该权限所属的上级标题id
        if(!!sonList.length){
            $.each(sonList,function (subIndex,subEle) {
                domStr+="<li data-selfId="+subEle.id+" data-upId="+subEle.upId+" class='permission btn btn-init'>"+subEle.menuName+"</li>";
            });
        }
        //数组拼接字符串DOM结构
        permissionList.push("<li class='clearfix'>"+
                                "<div class='col-sm-2 permission-title'>"+ele.menuName+"</div><ul class='col-sm-9 permission-content'>"+domStr+"</ul>"+
                            "</li>");

    });
    //渲染权限列表面板
    $permissionPanel.html(permissionList.join(""));
    $permission=$permissionPanel.find(".permission");//获取所有的权限名称DOM
});
$department.off("change").on("change",function (e) {
    var RoleId=$roleName.val();
    var permissionIdArr=[];
    handler({
        roleId:RoleId,
        PermissionList:permissionIdArr,
        permissionSelector:$permission
    });

});
//为公司职务绑定事件,监控职务名称的变化
$roleName.off("change").on("change",function (e) {
    var $this=$(this);
    //当职务发生了变化，获取当前职务id，并声明一个空数组selfPermissionIdArr，用来放置改职务下所拥有的权限id
    var selfRoleId=$this.val();
    var selfPermissionIdArr=[];
    handler({
        roleId:selfRoleId,
        PermissionList:selfPermissionIdArr,
        permissionSelector:$permission
    });
});
function handler(options) {
    var roleId=options.roleId;
    var PermissionList=options.PermissionList;
    var permissionSelector=options.permissionSelector;
    permissionSelector.removeClass("btn-checked");//清除上一次的渲染记录.重置所有的权限名称样式为初始状态
    if(!!roleId){
        //当职务被选定了以后,判断该职务是否是有值的,如果是有值的,那么就根据该职务id发送请求,获取该职务  所拥有的权限
        $.post(window.globalHost + '/agent-sys/admin/role/getDetail.do',{id:roleId}).success(function (data) {
            var record=common.transformData(data);
            var resultMenus=record['menus'];
            //获取该职务所拥有的权限标题数组，遍历该数组，将每一个权限id放进数组PermissionList中，便于筛选
            $.each(resultMenus,function (idx,ele) {
                PermissionList.push(ele['menuId']);
            });
            //遍历所有的权限DOM。如果在权限标签挂载的权限id和数组PermissionList内的权限id一致，就为这个权限标签增加选中样式类名"btn-checked"
            $.each(permissionSelector,function (idx, eleDom) {
                var $item=$(eleDom);
                if(PermissionList.indexOf($item.attr("data-selfId"))>-1){
                    $item.addClass("btn-checked");
                }
            });
            //为异步操作添加加闭包，给本职务下的所有权限添加绑定事件，添加或者删除该职务的某项权限
            (function () {
                permissionSelector.off("click").on("click",function (e) {
                    var $this=$(this);
                    var sendData={};
                    var addPermissionUrl=window.globalHost + '/agent-sys/admin/role/addAccess.do';
                    var removePermissionUrl=window.globalHost + '/agent-sys/admin/role/removeAccess.do';
                    var selfPermissionId=$this.attr("data-selfId");
                    //组装发送数据，无论是添加还是删除某项权限，都需要向后台发送的参数字段，id：所属职务id，menuId：该权限的id
                    sendData.id=roleId;
                    sendData.menuId=selfPermissionId;
                    //判断确定当前所属的职务是有值的，并且要操作更改的权限也是有值的
                    if(!!roleId&&!!selfPermissionId){
                        if($this.hasClass("btn-checked")){
                            //如果当前权限是本职务已经拥有的，需要删除该权限，调用删除权限的接口
                            $.post(removePermissionUrl,sendData).success(function (data) {
                                var record=common.transformData(data);
                                if(record['code']==="0"){
                                    //如果权限删除成功，权限背景色更新为灰色
                                    $this.removeClass("btn-checked");
                                    return false;
                                }else{
                                    layer.alert(record.res.msg);
                                }
                            });
                        }else{
                            //如果当前权限是未拥有的，需要为本职务添加该权限，调用添加权限的接口
                            $.post(addPermissionUrl,sendData).success(function (data) {
                                var record=common.transformData(data);
                                if(record['code']==="0"){
                                    //如果权限添加成功，权限背景色更新为绿色
                                    $this.addClass("btn-checked");
                                    return false;
                                }else{
                                    layer.alert(record.res.msg);
                                }
                            });
                        }
                    }
                })
            })();
        });
    }else{
        permissionSelector.off("click");
    }
}